<!--升级任务列表-->
<template>
  <div class="firmware-list">
    <div class="header">
      <div class="title">任务列表</div>
      <el-button
        :disabled="rolesCode === 'SALE'"
        type="add"
        size="14"
        icon="el-icon-plus"
        @click="dialogVisible = true">新建升级任务</el-button>
    </div>
    <el-table :data="tableData" style="width: 100%" :header-cell-style="{ background: '#F5F6F7' }" size="medium">
      <el-table-column prop="name" label="任务名称"> </el-table-column>
      <el-table-column prop="createTime" label="创建时间"> </el-table-column>
      <el-table-column :formatter="statusFormatter" label="状态"></el-table-column>
      <el-table-column fixed="right" label="操作" width="270">
        <template slot-scope="scope">
          <el-button type="text" size="operate" @click="handleDetails(scope.row)">详情</el-button>
          <el-button
            v-if="scope.row.state == 0"
            type="text"
            size="operate"
            :disabled="rolesCode === 'SALE'"
            @click="terminateUpgradeTaskFun(scope.row)">终止</el-button>
          <el-button
            v-if="scope.row.state == 2"
            type="text"
            size="operate"
            :disabled="rolesCode === 'SALE'"
            @click="deleteUpgradeTaskFun(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="current"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>

    <el-dialog
      v-loading="uploadLoading"
      title="新建升级任务"
      :visible.sync="dialogVisible"
      width="628px"
      :before-close="handleClose"
      :close-on-click-modal="false"
      custom-class="upgrade-task-dialog">
      <el-form ref="form" :rules="rules" :model="form" label-width="190px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="任务名称" prop="name">
              <template #label>
                <span>任务名称</span>&nbsp;
                <el-tooltip content="支持中英文和数字,长度2-32,名称不可重复" placement="bottom">
                  <i class="iconfont icon-wenhao"></i>
                </el-tooltip>
              </template>
              <el-input v-model="form.name" maxlength="32" placeholder="请输入任务名称">
              </el-input>
            </el-form-item>
            <el-form-item label="升级版本号" prop="upgradeVersion">
              <el-input
                v-model="form.upgradeVersion"
                minlength="1"
                :disabled="true"
                show-word-limit
                placeholder="当前版本号"></el-input>
            </el-form-item>
            <el-form-item label="可升级版本号（可多选）" prop="upgradeableVersionList">
              <el-select
                v-model="form.upgradeableVersionList"
                multiple
                placeholder="请选择升级版本号"
                clearable
                @change="downgradeVersionChange">
                <el-option
                  v-for="item in upgradeableFirmwareIdOptions"
                  :key="item.id"
                  :label="item.version"
                  :value="item.version">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="升级范围" prop="upgradeRange">
              <el-radio-group v-model="form.upgradeRange">
                <el-radio :label="0">全部设备</el-radio>
                <el-radio :label="1">特定设备</el-radio>
                <el-radio :label="2">特定标签</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="form.upgradeRange == 1" label="" prop="deviceIdList">
              <el-input v-model="form.deviceIdList" type="textarea" :rows="2" placeholder="请输入设备ID,多个设备之间以“ ; ”间隔">
              </el-input>
            </el-form-item>
            <el-form-item v-if="form.upgradeRange == 2" label="" prop="deviceTagId">
              <el-select v-model="form.deviceTagId" placeholder="请选择标签">
                <el-option
                  v-for="item in labelsList"
                  :key="item.id"
                  :label="item.tagName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="14" @click="handleClose()">取 消</el-button>
        <el-button type="primary" size="14" @click="submitForm('form')">保存</el-button>
      </span>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-drawer title="升级任务详情" :visible.sync="drawer" :direction="direction" size="720px">
      <template #title>
        <div class="custom-header">
          <span>升级任务详情</span>
          <span class="left width-60">版本号：</span><span class="right">{{ taskInfo.upgradeVersion }}</span>
          <div class="status">
            <div class="status-icon"></div>
            <div>{{ taskInfo.state }}</div>
          </div>
        </div>
      </template>
      <div v-loading="taskLoading">
        <div class="taskInfo">
          <div class="InfoTitle">任务基本信息
            <el-button
              type="add"
              size="mini"
              icon="el-icon-refresh-right"
              class="refresh"
              @click="handleDetails">刷新</el-button> </div>
          <div class="martop-16"><span class="left">任务名称</span><span class="right">{{ taskInfo.name }}</span></div>
          <div class="martop-16"><span class="left">升级版本号</span><span class="right">{{ form.upgradeVersion }}</span></div>
          <div class="martop-16"><span class="left">可升级版本号</span><span class="right">{{ taskInfo.upgradeableVersionList
          }}</span> </div>
        </div>
        <div class="taskInfo">
          <div class="InfoTitle">任务执行结果</div>
          <div class="martop-16"><span class="left">可升级设备数</span><span class="right">{{ taskInfo.deviceTotalNumber
          }}</span></div>
          <div class="martop-16"><span class="left">升级成功设备数</span><span class="right">{{ taskInfo.deviceSuccessNumber
          }}</span></div>
          <div class="martop-16"><span class="left">升级失败设备数</span><span class="right">{{ taskInfo.deviceFailureNumber
          }}</span></div>
          <div class="martop-16"><span class="left">未升级设备数</span><span class="right">{{
            taskInfo.deviceNotStartNumber }}</span></div>
          <a :href="dynamicLink" rel="opener" target="_blank">
            <el-button
              type="add"
              size="mini"
              class="refresh">查看ota任务具体数据</el-button>
          </a>
        </div>
      </div>

    </el-drawer>
  </div>
</template>
<script>
import { getUpgradeTaskList, getUpgradeVersionList, addUpgradeTask, getUpgradeTaskInfo, terminateUpgradeTask, deleteUpgradeTask } from "@/api/product/product-details";
import { getList } from '@/api/device-identity-auth/equipment-labels'
import { mapGetters } from 'vuex'
export default {
  name: "testDetails",
  data() {
    const validateDeviceUuidList = (rule, value, callback) => {
      if (this.form.upgradeRange === 1 && value === '') {
        callback(new Error('请输入设备ID'))
      } else {
        const deviceList = this.form.deviceIdList.split(/[;；\s]/)
        if (this.form.upgradeRange === 1 && deviceList.length > 32) {
          callback(new Error('输入设备id最多不超过32个'))
        } else {
          callback()
        }
      }
    }
    const validateLabelsList = (rule, value, callback) => {
      if (this.form.upgradeRange === 2 && this.deviceTagId === '') {
        callback(new Error('请选择标签'))
      } else {
        callback()
      }
    }
    return {
      tableData: [], // 表格数据
      dialogVisible: false,
      form: {
        name: "", //升级任务名称
        upgradeFirmwareId: '', //当前升级固件id
        upgradeVersion: '', //当前升级固件版本
        upgradeableFirmwareIdList: '', //可升级版本id列表
        upgradeableVersionList: '', //可升级版本列表
        upgradeRange: '', //升级类型 (0:全部设备，1:特定设备)
        deviceIdList: '', //设备Uid列表
        deviceTagId: '' // 设备标签选中值
      },
      rules: {
        name: [
          { required: true, message: '请输入任务名称', trigger: 'blur' },
          { min: 2, max: 32, message: '请输入规范的任务名称', trigger: 'blur' },
          { validator: this.validateName, trigger: 'blur' }
        ],
        upgradeableVersionList: [{ required: true, message: "请选择可升级版本号", trigger: "blur" }],
        upgradeRange: [{ required: true, message: "请选择升级范围", trigger: "blur" }],
        deviceIdList: { validator: validateDeviceUuidList, trigger: 'blur' },
        deviceTagId: [
          { required: true, message: '请选择标签', trigger: 'change' },
          {},
          { validator: this.validateLabelsList, trigger: 'change' }
        ]
      },
      uploadLoading: '', //新建升级任务弹窗的loading
      firmwareId: '', //当前固件id
      current: 1, //当前页面
      size: 10, //一页展示多少条
      total: 0, //总条数
      stateList: [
        //状态
        { value: 0, label: "执行中" },
        { value: 1, label: "执行完成" },
        { value: 2, label: "终止" }
      ],
      version: '', //当前版本号
      productId: "", //当前产品id
      drawer: false, //升级任务详情弹窗
      direction: 'rtl', //升级任务详情弹窗方向
      taskInfo: '', //升级任务详情弹窗展示信息
      taskId: '', //当前详情的升级任务id
      taskLoading: false, //升级任务详情弹窗loading
      upgradeableFirmwareIdOptions: '', // 可升级版本list
      labelsList: [], // 特定标签列表
    }
  },
  computed: {
    ...mapGetters(['rolesCode']),
    dynamicLink() {
      return `#/product/product-details/taskExecutionRecord?taskId=${this.taskId}`;
    }
  },
  created() { },
  mounted() {
    this.productId = this.$route.query.productId
    this.firmwareId = this.$route.query.firmwareId
    this.version = this.$route.query.version
    this.form.upgradeFirmwareId = this.$route.query.firmwareId //当前固件id
    this.form.upgradeVersion = this.$route.query.version //当前升级固件版本
    this.getUpgradeVersionListFun()
    this.getUpgradeTaskListFun()
    this.queryLabelsList()
  },
  methods: {
    // 任务名称校验
    validateName(rule, value, callback) {
      const flag = new RegExp(/^[\u4E00-\u9FA5A-Za-z0-9]+$/).test(value)
      if (!flag) {
        callback(new Error('请输入规范的任务名称'))
      } else {
        callback()
      }
    },
    // 升级任务详情
    handleDetails(row) {
      this.drawer = true
      this.taskLoading = true
      if (row.id) {
        this.taskId = row.id
      }
      const params = {
        taskId: row.id || this.taskId
      }
      getUpgradeTaskInfo(params).then((res) => {
        this.taskInfo = res.data.data
        this.taskInfo.state = this.statusFormatter(res.data.data)
        this.taskLoading = false
      }).catch((err) => {
        this.$message.error(err.message)
        this.taskLoading = false
      })
    },
    /**
     * 特定标签列表
     */
     queryLabelsList(condition, tagName) {
      this.currentPage = condition === 'search' ? 1 : this.currentPage
      const params = {
        size: 9999,
        current: 1
      }
      getList(params).then(res => {
        this.labelsList = res.data.data.records
      }).catch(err => {
        this.$message.error(err.message)
      }).finally(() => {
      })
    },
    // 新建升级任务弹窗关闭
    handleClose() {
      this.dialogVisible = false
      this.$refs['form'].resetFields()
    },
    // 每页条数改变时触发
    handleSizeChange(val) {
      this.size = val
      this.getUpgradeTaskListFun()
    },
    // 当前页变时触发
    handleCurrentChange(val) {
      this.current = val
      this.submitForm('form')
      this.getUpgradeTaskListFun()
    },
    //状态格式化
    statusFormatter(val) {
      const label = this.stateList.find((option) => option.value === val.state).label || "-"
      return label
    },

    // 删除升级任务
    deleteUpgradeTaskFun(row) {
      const params = {
        taskId: row.id
      }
      this.$confirm('升级任务删除后不可恢复，请谨慎操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUpgradeTask(params).then((res) => {
          this.getUpgradeTaskListFun()
        }).catch((err) => {
          this.$message.error(err.message)
        })
      })
    },
    // 终止测试任务
    terminateUpgradeTaskFun(row) {
      const params = {
        taskId: row.id
      }
      terminateUpgradeTask(params).then((res) => {
        this.getUpgradeTaskListFun()
      }).catch((err) => {
        this.$message.error(err.message)
      })
    },
    // 获取升级任务可升级版本号
    getUpgradeVersionListFun() {
      const params = { firmwareId: this.firmwareId }
      getUpgradeVersionList(params).then((res) => {
        this.upgradeableFirmwareIdOptions = res.data.data
      }).catch((res) => {

      })
    },
    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addTestTaskFun()
        } else {
          return false
        }
      })
    },
    // 新建升级任务
    addTestTaskFun() {
      this.uploadLoading = true
      this.form.upgradeableVersionList = this.form.upgradeableVersionList.join(';')
      addUpgradeTask(this.form).then((res) => {
        this.$message.success('新建成功')
        this.handleClose()
        this.getUpgradeTaskListFun()
        this.dialogVisible = false
        this.$refs['form'].resetFields()
        this.uploadLoading = false
      }).catch((err) => {
        this.$message.error(err.message)
        this.uploadLoading = false
        this.form.upgradeableVersionList = this.form.upgradeableVersionList.split(';');
      })
    },
    // 获取升级任务列表
    getUpgradeTaskListFun() {
      const params = {
        size: this.size,
        current: this.current,
        firmwareId: this.firmwareId
      }
      getUpgradeTaskList(params).then((res) => {
        this.tableData = res.data.data.records
        this.total = res.data.data.total
      }).catch((err) => {
        this.$message.error(err.message)
      })
    },
    // 获取升级固件id
    downgradeVersionChange(list) {
      var main = this
      var concatenatedIds = list.map(version => {
        var foundItem = main.upgradeableFirmwareIdOptions.find(item => {
          return item.version === version
        })
        return foundItem ? foundItem?.id : null
      }).filter(id => {
        return id !== null
      }).join(';')
      this.form.upgradeableFirmwareIdList = concatenatedIds
    }
  }
}
</script>
<style lang="scss" scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

::v-deep .el-textarea .el-input__count {
  background: transparent;
  right: 20px;
}

::v-deep .el-dialog__body {
  padding: 32px 48px 36px 38px;
}

::v-deep .el-form-item__label {
  color: #808080;
}

::v-deep .el-input-group__append {
  background-color: #ffffff;
  color: #808080;
}

::v-deep .el-button+.el-button {
  margin-left: 16px;
}

::v-deep .name-input .el-input__inner {
  padding-left: 15px;
  padding-right: 48px;
  background: transparent;
}

::v-deep .el-table__fixed-right-patch {
  background-color: #F5F6F7;
}

.title {
  font-weight: 600;
  font-size: 14px;
}

.header {
  margin-top: 32px;
}

::v-deep .el-select {
  width: 100%;
}

::v-deep .el-drawer__header {
  padding: 17px 0px 17px 20px;
  border: 1px solid #E5E6E9;
  font-weight: 600;
  color: #252525;
  font-size: 16px;
  margin-bottom: 0px;
}

.taskInfo {
  margin: 32px 0 0 74px;

  &:nth-child(2) {
    margin-top: 40px;
  }

  .InfoTitle {
    font-weight: 600;
    font-size: 14px;
  }

  .martop-16 {
    margin-top: 16px;
  }


  .refresh {
    padding: 7px 8px 6px;
    float: right;
    margin-right: 20px;
  }
}

.left {
  color: #808080;
  font-size: 14px;
  display: inline-block;
  width: 133px;
}

.right {
  color: #252525;
  font-size: 14px;
}

.status {
  float: right;
  padding: 3px 8px;
  background: rgba(12, 163, 209, 0.15);
  border-radius: 18px 18px 18px 18px;
  display: flex;
  align-items: center;
  font-weight: 400;
  color: #0CA3D1;
  font-size: 14px;
  margin-left: 33px;

  .status-icon {
    width: 6px;
    height: 6px;
    background: #0CA3D1;
    border-radius: 6px;
    margin-right: 6px;
  }
}

.width-60 {
  width: 60px;
  margin-left: 25px;
}

::v-deep .upgrade-task-dialog .el-dialog__body {
  padding: 20px 60px 20px 40px !important;
}
</style>
